package com.chucang.shucang.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.chucang.shucang.common.base.redis.RedisUtil;
import com.chucang.shucang.common.base.service.impl.CrudServiceImpl;
import com.chucang.shucang.oms.constant.OmsCacheConstant;
import com.chucang.shucang.oms.dao.CollectionOrderItemDao;
import com.chucang.shucang.oms.dto.CollectionOrderItemDTO;
import com.chucang.shucang.oms.entity.CollectionOrderBaseEntity;
import com.chucang.shucang.oms.entity.CollectionOrderItemEntity;
import com.chucang.shucang.oms.executor.MybatisBatchExecutor;
import com.chucang.shucang.oms.service.CollectionOrderItemService;
import com.github.yitter.idgen.YitIdHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;


/**
 * @author flitsneak flitsneak@gmail.com
 * @since 1.0.0 2022-10-12
 */
@Service
@RequiredArgsConstructor
public class CollectionOrderItemServiceImpl extends CrudServiceImpl<CollectionOrderItemDao, CollectionOrderItemEntity, CollectionOrderItemDTO> implements CollectionOrderItemService {

    private final MybatisBatchExecutor mybatisBatchExecutor;
    private final RedisUtil redisUtil;

    @Override
    public boolean batchSaveItems(CollectionOrderBaseEntity orderBaseEntity) {
        ArrayList<CollectionOrderItemEntity> itemList = new ArrayList<>(64);
        for (int i = 0; i < orderBaseEntity.getOrderNum(); i++) {
            //TODO 原型模式优化
            CollectionOrderItemEntity collectionOrderItemEntity = new CollectionOrderItemEntity();
            BeanUtil.copyProperties(orderBaseEntity, collectionOrderItemEntity);
            collectionOrderItemEntity.setSerialNum((Integer) redisUtil.popListValue(String.format(OmsCacheConstant.COLLECTION_SERIAL_NUMS, orderBaseEntity.getCollectionId())));
            collectionOrderItemEntity.setId(YitIdHelper.nextId());
            itemList.add(collectionOrderItemEntity);
        }
        mybatisBatchExecutor.insertOrUpdateBatch(itemList, CollectionOrderItemDao.class, (list, dao) -> dao.insertBatch(list));
        return true;
    }
}